/**
 *******************************************************************************
 * \brief   CAS EBX Project Work "Kaffeemaschine"
 *
 * \file    writeToDevice.c
 * \version 1.0
 * \date    18.08.2010
 * \author  Liechti Beat
 * 
 * \details	writes an int to a device
 * \details build with: 
 * \details gcc writeToDevice.c -o writeToDevice
 * \details then run with (example):
 * \details writeToDevice /dev/c2service 5
 *
 * \remark  Last Modifications:
 * \remark  V1.0, 18.08.2010   Initial release
 *******************************************************************************
 **/

#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <time.h>
#include <sys/times.h>
#include <sched.h>

#define RETCODE_SUCCESS		0
#define RETCODE_ERROR		-1

void usage(char *progname)
{
	printf("usage:\n\t%s /dev/<c2device> <int>\n", progname);
}

int main(int argc, char** argv)
{
	int retCode = -RETCODE_ERROR;
	if (argc == 3)
	{
		// -- expecting a string argv[1]
		char *devicePath = argv[1];
		// -- expecting an int in argv[2]
		int value;
		if (sscanf(argv[2], "%d", &value) != 1)
		{
			printf("ERROR: value is not an int, aborting\n");
		}
		else
		{
			int fd = open(devicePath, O_WRONLY);
			if (fd >= 0)
			{
				ssize_t size = write(fd, &value, sizeof(value));
				if (size != sizeof(value))
				{
					printf("failed to write value, got return code %ld\n", (long)size);
					retCode = EFAULT;
				}
				else
				{
					printf("sucessfully wrote value: %d\n", value);
					retCode = RETCODE_SUCCESS;
				}
				close(fd);
			}
			else
			{
				printf("failed to open file, got return code %d\n", fd);
			}
		}
	}
	else
	{
		usage(argv[0]);
	}
	return retCode;
}
